using UnityEngine;
using UnityEditor;

namespace LCH
{
    /// <summary>
    /// 网格绘制器 - 画笔相关功能模块
    /// </summary>
    public partial class LchMeshPainter
    {
        /// <summary>
        /// 根据网格大小设置默认画笔大小
        /// </summary>
        void SetDefaultBrushSize()
        {
            var mesh = selectObject.sharedMesh;
            var size = mesh.bounds.size;
            float _m = System.Math.Max(size.x, size.y);
            _m = System.Math.Max(size.x, _m);
            _m *= 0.02f;
            brushSize = brushSize < _m ? _m : brushSize;
        }
        
        /// <summary>
        /// 场景相机引用
        /// </summary>
        Camera sceneCamera = null;
        
        /// <summary>
        /// 更新画笔位置和方向
        /// </summary>
        /// <param name="sceneView">场景视图</param>
        void UpdateBrush(SceneView sceneView)
        {
            Camera cam = sceneView.camera;
            sceneCamera = cam;
            FixColliderPosition();
            Vector2 mousePosition = Event.current.mousePosition;
            int id = GUIUtility.GetControlID(FocusType.Passive);
            Ray ray = HandleUtility.GUIPointToWorldRay(mousePosition);
            selectMeshCollider.gameObject.hideFlags = HideFlags.DontSaveInEditor| HideFlags.DontSaveInBuild | HideFlags.HideInHierarchy;
            RaycastHit raycastHit;
            if (selectMeshCollider.Raycast(ray, out raycastHit, 5000f))
            {
                isMouseOnMesh = true;
                brush.transform.position = raycastHit.point;
                brush.transform.up = cam.transform.up;
                brush.transform.LookAt(raycastHit.point + ray.direction, cam.transform.up);
                brush.transform.localScale = new Vector3(brushSize, brushSize, brushSize);
          
                Shader.SetGlobalMatrix("worldToBrush", brush.transform.worldToLocalMatrix);
                if (isDragging)
                {
                    Vector2 dir0 = raycastHit.textureCoord - lastUV0;
                    Vector2 dir1 = raycastHit.textureCoord2 - lastUV1;
                    if (dir0.magnitude>0)
                    {
                        dir0.Normalize();
                        dir1.Normalize();
                        dragDirect = new Vector4(dir0.x*0.5f+0.5f, dir0.y*0.5f+0.5f, dir1.x*0.5f+0.5f, dir1.y*0.5f+0.5f);
                        Shader.SetGlobalVector("_GlobalBrushDir", dragDirect);
                        //Debug.LogError("_GlobalBrushDir = "+ dragDirect);
                        lastUV0 = raycastHit.textureCoord;
                        lastUV1 = raycastHit.textureCoord2;
                    }
                }
            }
            else
            {
                isMouseOnMesh = false;
                brush.transform.position = new Vector3(-10000f, -10000f, -10000f);
                brush.transform.forward = Vector3.forward;
                brush.transform.localScale = new Vector3(brushSize, brushSize, brushSize);

                Shader.SetGlobalMatrix("worldToBrush", brush.transform.worldToLocalMatrix);

                 
            }
        }

        /// <summary>
        /// 用于绘制画笔纹理的相机
        /// </summary>
        Camera rtCamera;
        
        /// <summary>
        /// 绘制画笔纹理到RenderTexture
        /// </summary>
        void DrawBrushTexture()
        {
            if (null == sceneCamera)
                return;
            if (null != lastSelectObject && null != brushMat2)
            {
                if (null == rtCamera)
                {
                    GameObject g = new GameObject("Brush Camrea");
                    rtCamera = g.AddComponent<Camera>();
                    g.hideFlags = HideFlags.DontSaveInEditor | HideFlags.DontSaveInBuild | HideFlags.HideInHierarchy;
                }

                rtCamera.enabled = false;

                rtCamera.clearFlags = CameraClearFlags.SolidColor;
                rtCamera.fieldOfView = 120f;

                rtCamera.targetTexture = brushTexture;
                rtCamera.transform.position = sceneCamera.transform.position;
                rtCamera.transform.rotation = sceneCamera.transform.rotation;

                rtCamera.backgroundColor = Color.black;
                rtCamera.cullingMask = 1 << 30;
                selectMeshRender.gameObject.layer = 30;
                brushMat2.SetTexture("_MainTex", brushMarks[selectedBrush]);
                selectMeshRender.sharedMaterial = brushMat2;

                
                if (uvMark == UVMark.UV0)
                {
                    Shader.DisableKeyword("_CHANNEL_UV2");
                    Shader.DisableKeyword("_CHANNEL_UV1");
                    Shader.EnableKeyword( "_CHANNEL_UV0");
 
                }
                else if (uvMark == UVMark.UV1)
                {
                    Shader.DisableKeyword("_CHANNEL_UV2");
                    Shader.DisableKeyword("_CHANNEL_UV0");
                    Shader.EnableKeyword( "_CHANNEL_UV1");
 
                }
                else if (uvMark == UVMark.UV2)
                {
                    Shader.DisableKeyword("_CHANNEL_UV0");
                    Shader.DisableKeyword("_CHANNEL_UV1");
                    Shader.EnableKeyword( "_CHANNEL_UV2");
       
                }
                rtCamera.Render();
                RenderTexture rt1 = RenderTexture.GetTemporary(brushTexture.width, brushTexture.height, 0);
                if (null == blurMat)
                    blurMat = new Material(Shader.Find("Hidden/GaussianBlur"));
                Graphics.Blit(brushTexture, rt1);
                Graphics.Blit(rt1,brushTexture, blurMat);
                RenderTexture.ReleaseTemporary(rt1);
                if (null == blendMat)
                    blendMat = new Material(Shader.Find("Hidden/BrushBlend"));
                blendMat.SetTexture("_MainTex", brushTexture);


                
                selectMeshRender.sharedMaterial = blendMat;
            }
        }
    }
}

